﻿using System.Xml.Linq;

namespace System.ServiceManager.Facade
{
    public class SCSMScheduleBuilder
    {
        private readonly XElement configNode = new XElement("WindowsWorkflowConfiguration");
        private readonly XElement parameters = new XElement("WorkflowParameters");
        private readonly XElement root = new XElement("Subscription");
        private int maxiumRunningTime = 300;
        private int retryOnExceptions;

        public SCSMScheduleBuilder(string assemblyName, string typeName)
        {
            configNode.Add(new XElement("AssemblyName", assemblyName));
            configNode.Add(new XElement("WorkflowTypeName", typeName));
        }

        public void AddParameter(string name, string value, string type)
        {
            parameters.Add(new XElement("WorkflowParameter"), value, new XAttribute("Name", name),
                           new XAttribute("Type", type));
        }

        public void SetMaxiumRunningTime(int seconds)
        {
            maxiumRunningTime = seconds;
        }

        public void SetRetryOnException(int seconds)
        {
            retryOnExceptions = seconds;
        }

        public string GetScheduleXml()
        {
            configNode.Add(parameters);
            if (retryOnExceptions > 0)
            {
                configNode.Add(new XElement("RetryExceptions", new XElement("RetryDelaySeconds", retryOnExceptions)));
            }
            if (retryOnExceptions > 0)
            {
                configNode.Add(new XElement("MaximumRunningTimeSeconds", maxiumRunningTime));
            }

            root.Add(configNode);

            return root.ToString();
        }
    }
}